Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

?? Operator results in "Unexpected Token" err when used in package #9468

Closed
arogozine opened this issue Aug 11, 2020 · 57 comments · Fixed by pass-culture/pass-culture-main#1972

Comments

@arogozine
Copy link

Describe the bug

If you import a package that uses ?? operator in code, create react app will fail when debugging.

This issue seems to appear only when debugging with such a library. (npm run start)

It builds (npm run build) without errors. So the toolchain for start vs build is in question here.

The operator works fine if used directly - not in the imported library code.

Did you try recovering your dependencies?

Issues occurred with multiple CRAs even with reinstalling node modules.

Which terms did you search for in User Guide?

Null Coalescing Operator Create React App
There seems to be an issue about optional chaining.

Environment

Windows 10 10.0.17763
npm 6.14.5
node 14.4.0
Google Chrome was used to ensure async, let, const, classes, and ?? support.

Steps to reproduce

  1. Create a React App with TypeScript (Haven't tried without TS)
  2. Create NPM package (TS with target ESNext, module, commonjs, declaration) that uses the ?? operator
  3. Use package in your app.
  4. Run start script

Expected behavior

The application should compile and run successfully when started or when built..

Actual behavior

The application fails to compile due to the ?? in the library.

Failed to Compile,
Unexpected token
You may need an additional loader to handle the result of these loaders.

Reproducible demo

If needed I can brew something up. This was found in a work project.

@bitjson
Copy link

bitjson commented Aug 12, 2020

I'm encountering this issue too – here's a repo to reproduce: https://github.com/bitjson/bitauth-cra (npm install && npm start):

./node_modules/@bitauth/libauth/build/module/lib/template/compiler.js 112:37
Module parse failed: Unexpected token (112:37)
File was processed with these loaders:
 * ./node_modules/babel-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
|   }), {});
|   const entityOwnership = Object.entries(template.entities).reduce((all, [entityId, entity]) => ({ ...all,
>     ...Object.keys(entity.variables ?? {}).reduce((entityVariables, variableId) => ({ ...entityVariables,
|       [variableId]: entityId
|     }), {})

The nullish coalescing operator works as expected in App.js, the error only seems to occur when the operator appears in an external dependency. (Try replacing this block with console.log(undefined ?? "success!") to confirm.)

Does anyone have any tips for how to debug this issue?

@bitjson
Copy link

bitjson commented Aug 12, 2020

As another data point, the bitauth-ide repo is running react-scripts at version 3.4.1, and the same library (@bitauth/libauth) is being imported without any errors. I'm still trying to figure out where the difference is.

@stale
Copy link

stale bot commented Sep 11, 2020

This issue has been automatically marked as stale because it has not had any recent activity. It will be closed in 5 days if no further activity occurs.

@stale stale bot added the stale label Sep 11, 2020
@bitjson
Copy link

bitjson commented Sep 15, 2020

For any TypeScript library authors having trouble with this, one workaround is to switch your compilation target from esnext to es2019. That will at least downlevel all nullish coalescing operators (??) so they don't trigger this bug.

@stale stale bot removed the stale label Sep 15, 2020
@bkiac
Copy link

bkiac commented Sep 17, 2020

Same error with react-scripts@3.4.3

@bkiac
Copy link

bkiac commented Sep 17, 2020

Changing browser targets from

 "browserslist": {
   "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
},

to

"browserslist": [
   ">0.2%",
  "not dead",
  "not op_mini all"
],

solved my issue.
I think #8445, #8526 could be related.
The issue is with aggressive browser targets like last 1 chrome version.

@arogozine
Copy link
Author

arogozine commented Oct 27, 2020

EDIT: Does having last 1 version for production makes this fail to build? I need to only support modern browsers - and transpilation increases bundle size.

Looks like 4.0.0 was released - but hasn't been properly tested.

Anyone can confirm that 4.0.0 still doesn't work with ?? (with or without TS)?

@ajayvikas
Copy link

Still getting the error on 4.0.0

../dist/index.modern.js 88:119
Module parse failed: Unexpected token (88:119)
File was processed with these loaders:
 * ../node_modules/@pmmmwh/react-refresh-webpack-plugin/loader/index.js
 * ../node_modules/babel-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
| 
|   function numberMask(rawValue = emptyString, config) {
>     rawValue = clean(rawValue, options, (config === null || config === void 0 ? void 0 : config.currentCaretPosition) ?? -1);
|     let [integer, fraction] = rawValue.split(period);
|     const hasPeriod = rawValue.indexOf(period) > -1;

@jxanders
Copy link

I tried the browserslist workaround from @bkiac and it worked for me (I could build debug but not production, now I can do both.) I'm on node 12.18.4 and the build is working fine for me. Oddly enough, my coworker cannot build the project for debug or production.

We don't have react-scripts installed so it might be an issue unrelated to react-scripts

@stale
Copy link

stale bot commented Dec 19, 2020

This issue has been automatically marked as stale because it has not had any recent activity. It will be closed in 5 days if no further activity occurs.

@stale stale bot added the stale label Dec 19, 2020
@arogozine
Copy link
Author

I'm gonna bump it. But the fix may be to use CRACO or something to configure 4.0.1.

@stale stale bot removed the stale label Dec 19, 2020
@Sinled
Copy link

Sinled commented Jan 21, 2021

any update here?

@jtomaszewski
Copy link

It happens to me on 4.0.1 , and I don't know any other workaround than forcing other libraries to not use esnext as the compilation target ( #9468 (comment) ). Which is far from nice.

@megargayu
Copy link

Is there any way to fix this with a javascript module? (The module I'm using gives the same error, but it was written in javascript). Do I have to edit the module myself?

@manjur2904
Copy link

./node_modules/@react-leaflet/core/esm/path.js 10:41
Module parse failed: Unexpected token (10:41)
File was processed with these loaders:

  • ./node_modules/babel-loader/lib/index.js
    You may need an additional loader to handle the result of these loaders.
    | useEffect(function updatePathOptions() {
    | if (props.pathOptions !== optionsRef.current) {
  const options = props.pathOptions ?? {};

| element.instance.setStyle(options);
| optionsRef.current = options;

------- herte is my error guys. please help me..

@flutterq
Copy link

[Solved] Failed to compile : ./node_modules/@react-leaflet/core/esm/path.js 10:41 Module parse failed: Unexpected token (10:41)

@tkforce
Copy link

tkforce commented Oct 17, 2022

Hey all, I've been looking at this the past couple days, and its still breaking.

Unfortunately the browse list change didn't work for me. I installed '@babel/plugin-proposal-nullish-coalescing-operator and added it to the plugins array, and also no luck.

Any other solutions I missed that I should look at? Thanks

@acrabb
According to the doc:
https://create-react-app.dev/docs/supported-browsers-features/#configuring-supported-browsers

When editing the browserslist config, you may notice that your changes don't get picked up right away. This is due to an issue in babel-loader not detecting the change in your package.json. A quick solution is to delete the node_modules/.cache folder and try again.

Deleting the node_modules/.cache works for me.

bonnie referenced this issue in bonnie/udemy-REACT-QUERY Oct 17, 2022
Update browserlist to avoid nullish coalescing error with most recent version of @tanstack/react-query (see https://github.com/facebook/create-react-app/issues/9468\#issuecomment-694191642)
bonnie referenced this issue in bonnie/udemy-REACT-QUERY Oct 17, 2022
Update browserlist to avoid nullish coalescing error with most recent version of @tanstack/react-query (see https://github.com/facebook/create-react-app/issues/9468\#issuecomment-694191642)
bonnie referenced this issue in bonnie/udemy-REACT-QUERY Oct 17, 2022
Update browserlist to avoid nullish coalescing error with most recent version of @tanstack/react-query (see https://github.com/facebook/create-react-app/issues/9468\#issuecomment-694191642)
bonnie referenced this issue in bonnie/udemy-REACT-QUERY Oct 17, 2022
Update browserlist to avoid nullish coalescing error with most recent version of @tanstack/react-query (see https://github.com/facebook/create-react-app/issues/9468\#issuecomment-694191642)
bonnie added a commit to bonnie/udemy-REACT-QUERY that referenced this issue Oct 17, 2022
Update browserlist to avoid nullish coalescing error with most recent version of @tanstack/react-query (see facebook/create-react-app#9468)
bonnie added a commit to bonnie/udemy-REACT-QUERY that referenced this issue Oct 17, 2022
Update browserlist to avoid nullish coalescing error with most recent version of @tanstack/react-query (see facebook/create-react-app#9468)
bonnie added a commit to bonnie/udemy-REACT-QUERY that referenced this issue Oct 17, 2022
Update browserlist to avoid nullish coalescing error with most recent version of @tanstack/react-query (see facebook/create-react-app#9468)
bonnie added a commit to bonnie/udemy-REACT-QUERY that referenced this issue Oct 17, 2022
Update browserlist to avoid nullish coalescing error with most recent version of @tanstack/react-query (see facebook/create-react-app#9468)
karrui added a commit to opengovsg/FormSG that referenced this issue Oct 25, 2022
was causing some compilation issues due to react scripts 4 and esm modules.

see facebook/create-react-app#9468 (comment)
@wftID3
Copy link

wftID3 commented Feb 7, 2023

Deleting the node_modules/.cache worked for me. Thanks @tkforce

@donkey-donkey
Copy link

Hey all, I've been looking at this the past couple days, and its still breaking.
Unfortunately the browse list change didn't work for me. I installed '@babel/plugin-proposal-nullish-coalescing-operator and added it to the plugins array, and also no luck.
Any other solutions I missed that I should look at? Thanks

@acrabb According to the doc: https://create-react-app.dev/docs/supported-browsers-features/#configuring-supported-browsers

When editing the browserslist config, you may notice that your changes don't get picked up right away. This is due to an issue in babel-loader not detecting the change in your package.json. A quick solution is to delete the node_modules/.cache folder and try again.

Deleting the node_modules/.cache works for me.

this worked for me. thanks much.

@shahsawar92
Copy link

{
  "name": "wits",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "webpack-dev-server --open --config webpack.dev.js",
    "build": "webpack --config webpack.prod.js",
    "analyz": "webpack --config webpack.analyzer.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.9.6",
    "@babel/plugin-transform-runtime": "^7.12.15",
    "@babel/polyfill": "^7.11.5",
    "@babel/preset-env": "^7.9.6",
    "@babel/preset-react": "^7.9.4",
    "@babel/runtime": "^7.12.13",
    "babel-loader": "^8.1.0",
    "clean-webpack-plugin": "^3.0.0",
    "css-loader": "^3.6.0",
    "file-loader": "^6.0.0",
    "html-loader": "^1.1.0",
    "html-webpack-plugin": "^4.3.0",
    "mini-css-extract-plugin": "^0.9.0",
    "node-sass": "^4.14.1",
    "optimize-css-assets-webpack-plugin": "^5.0.3",
    "sass-loader": "^8.0.2",
    "style-loader": "^1.2.1",
    "webpack": "^4.43.0",
    "webpack-bundle-analyzer": "^3.8.0",
    "webpack-cli": "^3.3.11",
    "webpack-dev-server": "^3.11.0",
    "webpack-merge": "^4.2.2"
  },
  "dependencies": {
    "@material-ui/core": "^4.11.0",
    "@material-ui/icons": "^4.9.1",
    "@material-ui/lab": "^4.0.0-alpha.56",
    "@sweetalert/with-react": "^0.1.1",
    "axios": "^0.20.0",
    "canvas-gauges": "^2.1.7",
    "classnames": "^2.2.6",
    "downsample-lttb": "0.0.1",
    "expression-eval": "^5.0.0",
    "i18next": "^19.4.5",
    "i18next-browser-languagedetector": "^4.2.0",
    "leaflet": "^1.9.3",
    "moment": "^2.29.4",
    "plotly.js": "^2.18.2",
    "prop-types": "^15.7.2",
    "react": "^16.13.1",
    "react-alert": "^7.0.1",
    "react-alert-template-basic": "^1.0.0",
    "react-container-dimensions": "^1.4.1",
    "react-dom": "^16.13.1",
    "react-draggable": "^4.4.5",
    "react-grid-layout": "^1.3.4",
    "react-helmet-async": "^1.3.0",
    "react-i18next": "^11.5.0",
    "react-leaflet": "^4.2.1",
    "react-plotly.js": "^2.5.1",
    "react-query": "^3.39.1",
    "react-responsive-carousel": "^3.2.23",
    "react-router-dom": "^5.2.0",
    "use-interval": "^1.4.0",
    "use-window-focus": "^1.4.2"
  },
  "browserslist": [
    ">0.2%",
    "not dead",
    "not op_mini all"
  ]
}

and i am encountering the same error how can i resolve this?

@ferm12
Copy link

ferm12 commented May 8, 2023

My solution to the [?? Operator results in "Unexpected Token"] ERROR was to install @babel/plugin-proposal-logical-assignment-operators and @babel/plugin-proposal-nullish-coalescing-operator
npm install --save-dev @babel/plugin-proposal-logical-assignment-operators @babel/plugin-proposal-nullish-coalescing-operator
then added to the babel.config.js file:

  presets: [
    [
      '@babel/preset-env',
      {
        modules: false,
      },
    ],
    '@babel/preset-react',
  ],
  plugins: [
    'styled-components',
    '@babel/plugin-proposal-class-properties',
    '@babel/plugin-syntax-dynamic-import',
    '@babel/plugin-proposal-nullish-coalescing-operator',	
    '@babel/plugin-proposal-logical-assignment-operators',
  ],
  env: {
    production: {
      only: ['app'],
      plugins: [
        'lodash',
        'transform-react-remove-prop-types',
        '@babel/plugin-transform-react-inline-elements',
        '@babel/plugin-transform-react-constant-elements',
        '@babel/plugin-proposal-nullish-coalescing-operator',	
        '@babel/plugin-proposal-logical-assignment-operators',
      ],
    },
    test: {
      plugins: [
        '@babel/plugin-transform-modules-commonjs',
        'dynamic-import-node',
      ],
    },
  },
};```

@shahsawar92
Copy link

Thanks this answer worked!

https://stackoverflow.com/a/67747605

Like @ferm12, you said @babel/plugin-proposal-nullish-coalescing-operator this solved the issue for me

@ferm12
Copy link

ferm12 commented May 10, 2023

@shahsawar92 I am glad you were able to solve your problem.

@chaitanya71998
Copy link

@ferm12 i am having an old repo which is at react 16 version. the above issue is still persisting even though I updated the configs in babel

dependencies{
      "react": "^16.12.0",
      "react-scripts": "3.2.0",    

babel.config.js

module.exports = {
   presets: ['@babel/preset-env'],
   plugins: [
      [
         '@babel/plugin-proposal-decorators',
         {
            legacy: true
         }
      ],
      '@babel/plugin-proposal-nullish-coalescing-operator',
      '@babel/plugin-proposal-logical-assignment-operators'
   ]
}

what is the issue here? is it with react versions? Could you give solution to this?
TIA.

@Chaoste
Copy link

Chaoste commented Oct 10, 2023

I just had this issue while using node 12 in an old environment, nvm i 18 && nvm use 18 solved it for me after the browserlist change didn't fix it in my case.

@dhiren-eng
Copy link

dhiren-eng commented Feb 26, 2024

The cause is exactly the same as #8526 which added support for nullish coalescing in the developers code (e.g. App.js) but not in node_modules.

Now that it is supported by all evergreen browsers it is reasonable to assume that there will be some NPM packages that do not transpile this.

I think the changes in #8526 should be added to https://github.com/facebook/create-react-app/blob/main/packages/babel-preset-react-app/dependencies.js until react-scripts is using a newer version of webpack that can handle this syntax.

I didn't want to change my browserslist because it would transpile other code unnecessarily, so I used CRACO.

npm install @babel/plugin-proposal-nullish-coalescing-operator --save-dev
// craco.config.js
module.exports = {
  babel: {
    plugins: [["@babel/plugin-proposal-nullish-coalescing-operator"]],
  },
};

@jamime Just curious if the whole node_modules are also parsed by a babel plugin would'nt it make it slower to start react app in dev mode or make hot reloading slower ?

@1161853339
Copy link

// craco.config.js
module.exports = {
  babel: {
    plugins: [["@babel/plugin-proposal-nullish-coalescing-operator"]],
  },
};

This code is the fast fix the issue.I use craco,add the babel plugin is well fix this. Thx @dhiren-eng

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.